package _21_多线程juc.demo01;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Map;

/**
 * 练习 Thread，实现多线程下载图片
 * 1. 引入 common io 包
 */
@Data
@AllArgsConstructor
public class MyThread1_1 extends Thread {

    private String url;
    private String fileName;

    @Override
    public void run() {
        try {
            // 下载图片，并打印当前线程名字
            FileUtils.copyURLToFile(new URL("url"), new File(fileName));
            System.out.println(fileName + ": Thread.currentThread().getName() = " + Thread.currentThread().getName());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        MyThread1_1 thread1 = new MyThread1_1(MyTestPictures.urlOfPic_1, MyTestPictures.fileNameOfPic_1);
        thread1.start();
        MyThread1_1 thread2 = new MyThread1_1(MyTestPictures.urlOfPic_2, MyTestPictures.fileNameOfPic_2);
        thread2.start();
        new MyThread1_1(MyTestPictures.urlOfPic_3, MyTestPictures.fileNameOfPic_3).start();
        new MyThread1_1(MyTestPictures.urlOfPic_4, MyTestPictures.fileNameOfPic_4).start();

        // 获取图片资源的 key,value；对每张图片，new 一个线程下载
        Map<String, String> sourceMap = MyTestPictures.getPictureSource();
        sourceMap.forEach((key, value) -> new MyThread1_1(key, value).start());
    }
}

